package cn.hnu.service;

import cn.hnu.domain.Users;
import cn.hnu.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 自定义的 UserDetailsService 实现，用于从数据库加载用户信息
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 从数据库查询用户
        Users user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 2. 根据role_id获取角色（需要先创建角色表或枚举）
        String role = switch (user.getRoleId()) {
            case 1 -> "ADMIN";
            case 2 -> "TEACHER";
            case 3 -> "STUDENT";
            default -> "USER";
        };

        // 3. 创建权限列表
        List<GrantedAuthority> authorities = Collections.singletonList(
            new SimpleGrantedAuthority("ROLE_" + role)
        );

        // 4. 返回Spring Security的User对象
        return new User(
            user.getUsername(),
            user.getPassword(), // 数据库中的密码应该是加密后的
            authorities
        );
    }
}